<?php

/**
 * @file
 * Provides theme overrides and implementations for the System module.
 */

/**
 * Preprocesses variables for html.tpl.php.
 */
function tweme_preprocess_html(&$vars) {
  _tweme_load_bootstrap();
  _tweme_load_html5shiv();
  _tweme_load_assets();
}

/**
 * Processes variables for html.tpl.php.
 */
function tweme_process_html(&$vars) {
  if ($body_top = _tweme_region_blocks_markup('body_top')) {
    $vars['page_top'] = '<div class="conceal">' . $body_top . '</div>' . $vars['page_top'];
  }
  if ($body_bottom = _tweme_region_blocks_markup('body_bottom')) {
    $vars['page_bottom'] .= '<div class="conceal">' . $body_bottom . '</div>';
  }
  $vars['head_bottom'] = _tweme_add_html_head_bottom();
}

/**
 * Preprocesses variables for page.tpl.php.
 */
function tweme_preprocess_page(&$vars) {
  $page = $vars['page'];

  // Prepare navbar menu:
  $vars['navbar_menu_tree'] = menu_tree(variable_get('menu_main_links_source', 'main-menu'));

  // Prepare navbar search form:
  $vars['navbar_search_form'] = FALSE;
  if (module_exists('search')) {
    $form = drupal_get_form('search_form');
    unset($form['basic']['keys']['#theme_wrappers']);
    $form['basic']['keys']['#attributes']['class'][] = 'search-query';
    $form['#attributes']['class'][] = 'navbar-search';
    $form['#attributes']['class'][] = 'navbar-search-elastic';
    $form['#attributes']['class'][] = 'hidden-phone';
    $form['#theme_wrappers'][] = 'pure_form_wrapper';
    $vars['navbar_search_form'] = $form;
  }

  // Add custom classes to navbar search form:
  $vars['navbar_search_form']['#attributes']['class'][] = 'pull-right';

  _add_breadcrumb();
//  _add_block_to_region($vars,'portal','nav_left','sidebar_first');
  _add_block_to_region($vars,'portal','nav_sales','sidebar_first');
  _add_block_to_region($vars,'portal','nav_service','sidebar_first');
//  _add_block_to_region($vars,'portal','nav_data','sidebar_first');
  _add_block_to_region($vars,'portal','nav_system','sidebar_first');
//  _add_block_to_region($vars,'portal','nav_stats','sidebar_first');

  // Add message alerting

  if (_view_chat_bubble()) {
    $vars['page']['alert_messages'] = '<a href="javascript:void(0);" ' .
        "onclick=\"javascript:void window.open('" . base_path() . "contact/chat','1446518728896', 'width=900,height=720,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=0,top=0');return false;\">" .
        '<img id="message_alert" src="' . base_path() . 'sites/all/themes/tweme/images/message-alert.png">
      <img id="message_alert_new" style="display:none" src="' . base_path() . 'sites/all/themes/tweme/images/message-alert_new.png"></a>';
  }
}

function _view_chat_bubble() {
  // company inside chat bubble
  global $user;
  return in_array('administrator', $user->roles) || in_array('销售员', $user->roles) || in_array('销售管理员', $user->roles) ||
          in_array('农化服务员', $user->roles) ||in_array('农化管理员', $user->roles)|| in_array('经销商', $user->roles) || in_array('公司领导', $user->roles);
}

function _add_breadcrumb()
{
    $breadcrumb = drupal_get_breadcrumb();
    // get menu item path and replace all add, edit/% with list
    $menu_item = menu_get_item();
    $menu_item_path = $menu_item['path'];
    $menu_item_path = str_replace("/add", "/list", $menu_item_path);
    $menu_item_path = str_replace("/edit/%", "/list", $menu_item_path);
//  if ('taxonomy/term/%' == $menu_item['path']) {
//    // set $breadcrumb by taxonomy
//    $term = taxonomy_term_load(arg(2));
//    $term_parent = taxonomy_get_parents($term->tid);
//    $v = taxonomy_vocabulary_load($term->vid);
//    $breadcrumb['1'] = "<a href=\"".base_path()."#\">".$v->name."</a>";
//    $i = 2;
//    foreach ($term_parent as $p) {
//      $breadcrumb[$i] = "<a href=\"".base_path()."taxonomy/term/".$p->tid."\">".$p->name."</a>";
//      $i++;
//    }
//    $breadcrumb[$i+1] = "<a href=\"#\">".drupal_get_title()."</a>";
//  } else if('qa' == $menu_item['path']){
//
//    $breadcrumb[1] = l('咨询问答','qa');
//  } else if('node/%' == $menu_item['path']){
//    // set $breadcrumb by node type
//    $node_has_breadcrumb = true;
//    $node = node_load(arg(1));
//    switch ($node->type) {
//      case 'product':
//        $term = taxonomy_term_load($node->field_product_category['und']['0']['tid']);
//        break;
//      case 'case':
//        $term = taxonomy_term_load($node->field_product_case['und']['0']['tid']);
//        break;
//      case 'knowledge':
//        $term = taxonomy_term_load($node->field_knowledge_category['und']['0']['tid']);
//        break;
//      default:
//        $node_has_breadcrumb = false;
//        break;
//    }
//    if('question'==$node->type){
//      $breadcrumb[1] = l('咨询问答','qa');
//    }
//    if ($node_has_breadcrumb) {
//      $term_parent = taxonomy_get_parents($term->tid);
//      $v = taxonomy_vocabulary_load($term->vid);
//      $breadcrumb['1'] = "<a href=\"" . base_path() . "#\">" . $v->name . "</a>";
//      $i = 2;
//      foreach ($term_parent as $p) {
//        $breadcrumb[$i] = "<a href=\"" . base_path() . "taxonomy/term/" . $p->tid . "\">" . $p->name . "</a>";
//        $i++;
//      }
//      $breadcrumb[$i] = "<a href=\"" . base_path() . "taxonomy/term/" . $term->tid . "\">" . $term->name . "</a>";
//      $breadcrumb[$i + 1] = "<a href=\"#\">" . drupal_get_title() . "</a>";
//    }
//  } else if('portal/%' == $menu_item['path']){
//    $breadcrumb['1'] = "<a href=\"#\">".drupal_get_title()."</a>";

    switch ($menu_item['path']) {
        case 'node/%':
            //node详情页
            $node = node_load(arg(1));
            switch ($node->type) {
                case 'consult':
                    $breadcrumb['1'] = "<a href=\"" . base_path() . "consult" . "\">" . "问专家" . "</a>";
//              $breadcrumb['2'] = "<a href=\"#\">" . drupal_get_title() . "</a>";
                    break;
                case 'case':
                    $breadcrumb['1'] = "<a href=\"" . base_path() . "node-list/" . $node->type . "\">" . "产品故事" . "</a>";
                    break;
                case 'knowledge':
                    $breadcrumb['1'] = "<a href=\"" . base_path() . "node-list/" . $node->type . "\">" . "农技知识" . "</a>";
                    break;
                case 'market':
                    $breadcrumb['1'] = "<a href=\"" . base_path() . "node-list/" . $node->type . "\">" . "农资市场" . "</a>";
                    break;
                case 'news':
                    $breadcrumb['1'] = "<a href=\"" . base_path() . "node-list/" . $node->type . "\">" . "农业动态" . "</a>";
                    break;
                case 'help':
                    $breadcrumb['1'] = "<a href=\"" . base_path() . "help/" . "\">" . "使用帮助" . "</a>";
                    break;
                case 'forum':
                    $breadcrumb['1'] = "<a href=\"" . base_path() . "forum/" . "\">" . "论坛" . "</a>";
                    break;
                default:
                    $breadcrumb['1'] = "<a href=\"#\">" . drupal_get_title() . "</a>";
                    break;
            }
            break;
        case 'consult':
            $breadcrumb['1'] = "<a href=\"" . base_path() . "consult" . "\">" . "问专家" . "</a>";
            break;
        case 'help':
            $breadcrumb['1'] = "<a href=\"" . base_path() . "help/" . "\">" . "使用帮助" . "</a>";
            break;
        case 'node-list':
            switch ($menu_item['map'][1]) {
                case 'case':
                    $breadcrumb['1'] = "<a href=\"" . base_path() . "node-list/" . $menu_item['map'][1] . "\">" . "产品故事" . "</a>";
                    break;
                case 'knowledge':
                    $breadcrumb['1'] = "<a href=\"" . base_path() . "node-list/" . $menu_item['map'][1] . "\">" . "农技知识" . "</a>";
                    break;
                case 'market':
                    $breadcrumb['1'] = "<a href=\"" . base_path() . "node-list/" . $menu_item['map'][1] . "\">" . "农资市场" . "</a>";
                    break;
                case 'news':
                    $breadcrumb['1'] = "<a href=\"" . base_path() . "node-list/" . $menu_item['map'][1] . "\">" . "农业动态" . "</a>";
                    break;
                default:
                    $breadcrumb['1'] = "<a href=\"#\">" . drupal_get_title() . "</a>";
                    break;
            }
            break;
        default:
            if(isset($menu_item['map'][0])) {
                switch ($menu_item['map'][0]) {
                    case 'account':
                        //我的账户/其他
                        $breadcrumb['1'] = "<a href=\"" . base_path() . "user" . "\">" . "我的账户" . "</a>";
                        $breadcrumb['2'] = "<a href=\"#\">" . drupal_get_title() . "</a>";
                        break;
                    case 'document_instance':
                        $m = menu_tree_all_data('menu-nonghua', 2);
                        $menu_item_path = "document_instance/list/" . $menu_item['map'][2];
                        foreach ($m as $level_1) {
                            foreach ($level_1['below'] as $level_2) {
                                if ($level_2['link']['link_path'] == $menu_item_path) {
                                    $breadcrumb['1'] = "<a href=\"" . base_path() . $level_1['link']['href'] . "\">" . $level_1['link']['title'] . "</a>";
                                    $breadcrumb['2'] = "<a href=\"" . base_path() . $level_2['link']['href'] . "\">" . $level_2['link']['title'] . "</a>";
                                    $breadcrumb['3'] = "<a href=\"#\">" . drupal_get_title() . "</a>";
                                }
                            }
                        }
                        break;
                    default:
                        //我的账户/账户信息特殊处理
                        if (isset($menu_item['map'])) {
                            if ($menu_item['map'][0] == 'employee' || $menu_item['map'][0] == 'farmer' || $menu_item['map'][0] == 'distributor') {
                                if ($menu_item['map'][1] == 'edit') {
                                    global $user;
                                    if ($menu_item['map'][2] == $user->uid) {
                                        $breadcrumb['1'] = "<a href=\"" . base_path() . "user" . "\">" . "我的账户" . "</a>";
                                        $breadcrumb['2'] = "<a href=\"#\">" . "基本信息" . "</a>";
                                        break;
                                    }
                                }
                            }
                        }
                        // 业务表格页 set $breadcrumb by menu_nonghua
                        $m = menu_tree_all_data('menu-nonghua', 2);
                        foreach ($m as $level_1) {
                            foreach ($level_1['below'] as $level_2) {
                                if ($level_2['link']['link_path'] == $menu_item_path) {
                                    $breadcrumb['1'] = "<a href=\"" . base_path() . $level_1['link']['href'] . "\">" . $level_1['link']['title'] . "</a>";
                                    $breadcrumb['2'] = "<a href=\"" . base_path() . $level_2['link']['href'] . "\">" . $level_2['link']['title'] . "</a>";
                                    $breadcrumb['3'] = "<a href=\"#\">" . drupal_get_title() . "</a>";
                                }
                            }
                        }
                }
            }
    }
    drupal_set_breadcrumb($breadcrumb);
}

function _add_block_to_region(&$vars, $module, $delta, $region)
{
    static $block_added = false; // only add one block
    if (!$block_added&&is_block_to_show($module, $delta)) {
        $vars['page'][$region][] = module_invoke($module, 'block_view', $delta);
        $block_added = true;
    }
}

function is_block_to_show($module, $delta)
{

//    $nav_visibility = array(
//      'portal_nav_sales' => array(
//        'portal/1',
//        'sales/sales_log/list',
//        'sales/monthly_report/list',
//        'stock_info/list',
//        'sales/invoice/list',
//        'brand_sales/list',
//        'competitors/list',
//        'capacity/list',
//        'plant_structure/list',
//        'retailstore/list',
//        'document_instance/list/10',
//      ),
//      'portal_nav_service' => array(
//        'portal/2',
//        'farmer/list',
//        'farmer/plant_info/list',
//        'farmer/soil_info/list',
//        'distributor/list',
//        'revisit/list',
//        'village/list',
//        'fertilizer_case/list',
//        'village/activity/list',
//        'experts_work/list',
//      ),
////      'portal_nav_stats' => array(
////        'portal/3',
////        'sales/monthly_report/stats',
////        'stock_info/stats',
////        'sales/invoice/stats',
////        'brand_sales/stats',
////        'competitors/stats',
////        'capacity/stats',
////        'plant_structure/stats',
////      ),
////      'portal_nav_data' => array(
////        'portal/4',
////
////      ),
//        'portal_nav_system' => array(
//            'portal/5',
//            'employee/list',
//            'manage-brand/list',
//            'sales/juris/list',
//            'manage-address',
//            'manage-fertilizer/list',
//            'genuine-code/list',
//            'sales/salesman_distributor_map/list',
//            'sales/distributor_assign_salesman/list',
//            'genuine_verification',
//            'manage_chat/agent/list',
//            'document_template/list',
//            'document_instance/list',
//            'manage_chat/friend/list',
//            'manage_chat/message/list',
//            'manage_chat/room/list',
//            'manage_chat/groups/list'
//      ),
//    );

    $page_visibility = array(
        'portal_nav_sales' => array(
            'portal/1',
            'brand_sales/*',
            'competitors/*',
            'capacity/*',
            'document_instance/*/10/*',
            'document_instance/*/10',
            'plant_structure/*',
            'retailstore/*',
            'sales/sales_log/*',
            'sales/monthly_report/*',
            'sales/invoice/*',
            'stock_info/*',
            'distributor/*',
            'document_instance/*',
        ),
        'portal_nav_service' => array(
            'portal/2',
            'manage-address',
            'manage-address/*',
            'metercomm-import',
            'experts_work/*',
            'farmer/*',
            'revisit/*',
            'fertilizer_case/*',
            'village/*',
            'plant_measure/*',
            'plant_measure_item/*',
            'experts/*',
            'special_activities/*',
            'gift/list',
            'gift/add',
            'gift/edit/*',
        ),
        'portal_nav_system' => array(
            'portal/5',
            'document_template/*',
            'employee/*',
            'gift/assign_list',
            'genuine-code/*',
            'genuine_verification',
            'manage-brand/*',
            'manage-fertilizer/*',
            'sales/juris/*',
            'sales/salesman_distributor_map/*',
            'sales/distributor_assign_salesman/*',
            'manage_chat/*',
            'manage_plant/*',
            'user/upgrade/*',
            'product_sku/*',
        ),
    );
    $menu_item = menu_get_item();
    switch ($index = $module . '_' . $delta) {
        case 'portal_nav_product':
            //add block nav_product to vocabulary product_category and node type product
            if ('taxonomy/term/%' == $menu_item['path']) {
                $term = taxonomy_term_load(arg(2));
                return ($term->vocabulary_machine_name == 'product_category');
            }
            if ('node/%' == $menu_item['path']) {
                $node = node_load(arg(1));
                return ($node->type == 'product');
            }
            break;
        case 'portal_nav_case':
            //add block nav_product to vocabulary product_category and node type product
            if ('taxonomy/term/%' == $menu_item['path']) {
              $term = taxonomy_term_load(arg(2));
              return ($term->vocabulary_machine_name == 'product_case');
            }
            if ('node/%' == $menu_item['path']) {
              $node = node_load(arg(1));
              return ($node->type == 'case');
            }
            break;
        case 'portal_nav_knowledge':
            //add block nav_product to vocabulary product_category and node type product
            if ('taxonomy/term/%' == $menu_item['path']) {
              $term = taxonomy_term_load(arg(2));
              return ($term->vocabulary_machine_name == 'knowledge_category');
            }
            if ('node/%' == $menu_item['path']) {
              $node = node_load(arg(1));
              return ($node->type == 'knowledge');
            }
          break;
        case 'portal_nav_system':
            if ('employee' == arg(0) && 'edit' == arg(1) && $GLOBALS['user']->uid == arg(2)) {
                return false;
            }

            return drupal_match_path($_GET['q'], implode("\n",$page_visibility[$index]));

            break;
        default:
//            $menu_item_href = $menu_item['href'];
//            $menu_item_href = preg_replace("(edit/.*)", "list", $menu_item_href);
//            $menu_item_href = str_replace("/add", "/list", $menu_item_href);
//            $menu_item_href = str_replace("/edit/", "/list", $menu_item_href);
//            return in_array($menu_item_href, $nav_visibility[$index]);


            return drupal_match_path($_GET['q'], implode("\n",$page_visibility[$index]));

            break;
    }
    return false;
}
/**
 * Processes variables for page.tpl.php.
 */
function tweme_process_page(&$vars) {
  $page = $vars['page'];

  // Provide additional variables to theme:
  $vars['navbar_brand'] = theme('navbar_brand', array(
    'name' => $vars['site_name'],
    'href' => $vars['front_page'],
    'logo' => $vars['logo'],
  ));
  $vars['navbar_menu'] = drupal_render($vars['navbar_menu_tree']);
  $vars['navbar_search'] = drupal_render($vars['navbar_search_form']);
  $vars['navbar_toggler'] = theme('navbar_toggler');
  $vars['preface'] = theme('preface', $vars);
  $vars['copyright'] = theme('copyright', array('name' => $vars['site_name']));

  // Prepare some useful variables:
  $vars['has_header'] = !empty($vars['title']) || !empty($vars['messages']);
  $vars['has_sidebar_first'] = !empty($page['sidebar_first']) || !empty($page['sidebar_first_affix']);
  $vars['has_sidebar_second'] = !empty($page['sidebar_second']) || !empty($page['sidebar_second_affix']);
  $vars['content_cols'] = 12 - 3 * (int) $vars['has_sidebar_first'] - 3 * (int) $vars['has_sidebar_second'];
}

/**
 * Overrides theme_menu_local_tasks().
 */
function tweme_menu_local_tasks(&$vars) {
  $out = '';
  if (!empty($vars['primary'])) {
    $vars['primary']['#prefix'] = '<ul class="nav nav-' . theme_get_setting('primary_tasks_style') . '">';
    $vars['primary']['#suffix'] = '</ul>';
    $out .= drupal_render($vars['primary']);
  }
  if (!empty($vars['secondary'])) {
    $vars['secondary']['#prefix'] = '<ul class="nav nav-' . theme_get_setting('secondary_tasks_style') . '">';
    $vars['secondary']['#suffix'] = '</ul>';
    $out .= drupal_render($vars['secondary']);
  }
  return $out;
}

/**
 * Overrides theme_item_list().
 */
function tweme_item_list($vars) {
  if (isset($vars['attributes']['class']) && in_array('pager', $vars['attributes']['class'])) {
      global $pager_total_items;
    unset($vars['attributes']['class']);
    foreach ($vars['items'] as $i => &$item) {
      if (in_array('pager-current', $item['class'])) {
        $item['class'] = array('active');
        $item['data'] = '<a href="#">' . $item['data'] . '</a>';
      }
      elseif (in_array('pager-ellipsis', $item['class'])) {
        $item['class'] = array('disabled');
        $item['data'] = '<a href="#">' . $item['data'] . '</a>';
      }
    }
    return '<div class="pagination pagination-centered">' . theme_item_list($vars) . "<div>共计{$pager_total_items[0]}条记录</div>". '</div>';
  }
  return theme_item_list($vars);
}

/**
 * Preprocesses variables for theme_button().
 */
function tweme_preprocess_button(&$vars) {
  $vars['element']['#attributes']['class'][] = 'btn';
  if (isset($vars['element']['#parents'][0]) && $vars['element']['#parents'][0] == 'submit') {
    $vars['element']['#attributes']['class'][] = 'btn-primary';
  }
}
